<template>
	<view class="uni-content">
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<!-- <button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button> -->
				<!-- 	<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button> -->
				<button class="uni-button" type="default" @click="$emit('closepop')">关闭菜单</button>
				<!-- <button class="uni-button" type="primary" @click="uploadExcel()" size="default">导入</button> -->
			</view>
		</view>

		<view class="uni-container">
			<view>
				<view class="left-content">
					<unicloud-db ref="udb" :collection="collectionList" field="s_id,name,type_subject,type_drive_id,video_link,video_name,test_paper_ids,sort,status,t_sort,
						type_subject{_id,name,s_id},test_paper_ids{_id,name,s_id},type_drive_id{_id,name,s_id}" :where="where"
						page-data="replace" :orderby="orderby" :getcount="true" :page-size="options.pageSize"
						:page-current="options.pageCurrent" v-slot:default="{data,pagination,loading,error,options}"
						:options="options" loadtime="manual" @load="onqueryload">
						<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
							type="selection" @selection-change="selectionChange">
							<uni-tr>
								<uni-th align="center" filter-type="search"
									@filter-change="filterChange($event, 's_id')" sortable
									@sort-change="sortChange($event, 's_id')">课程ID</uni-th>
								<uni-th align="center" filter-type="search"
									@filter-change="filterChange($event, 'name')" sortable
									@sort-change="sortChange($event, 'name')">课程昵称</uni-th>
								<uni-th align="center" sortable @sort-change="sortChange($event, 'type_subject')">科目类型
								</uni-th>
								<uni-th align="center" sortable @sort-change="sortChange($event, 'type_drive_id')">驾驶证类型
								</uni-th>
								<!-- 			<uni-th align="center" sortable @sort-change="sortChange($event, 'video_link')">视频链接</uni-th>
								<uni-th align="center" sortable @sort-change="sortChange($event, 'video_name')">视频昵称</uni-th> -->
								<!-- <uni-th align="center" sortable @sort-change="sortChange($event, 'test_paper_ids')">试卷</uni-th> -->
								<!-- 	<uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'sort')"
									sortable @sort-change="sortChange($event, 'sort')">排序</uni-th>
								<uni-th align="center" filter-type="select"
									:filter-data="options.filterData.status_localdata"
									@filter-change="filterChange($event, 'status')">启用状态</uni-th> -->
								<uni-th align="center">操作</uni-th>
							</uni-tr>
							<uni-tr v-for="(item,index) in data" :key="index">
								<uni-td align="center">{{item.s_id}}</uni-td>
								<uni-td align="center">{{item.name}}</uni-td>
								<uni-td align="center">
									<view v-for="(isb,ids) in item.type_subject">
										{{isb.name}}({{isb.s_id}})
									</view>

								</uni-td>
								<uni-td align="center">
									<view v-for="(item,index) in item.type_drive_id">
										<uni-tag :text="item.name" type="primary"></uni-tag>
									</view>
								</uni-td>
								<!-- 	<uni-td align="center">
									<view v-for="(item,index) in item.video_link">
										<uni-tag :text="item" type="royal"></uni-tag>
									</view>
								</uni-td>
								<uni-td align="center">
									<view v-for="(item,index) in item.video_name">
										<uni-tag :text="item" type="royal"></uni-tag>
									</view>
								</uni-td> -->
								<!-- <uni-td align="center">
									<view v-for="(item,index) in item.test_paper_ids" >
										<uni-tag :text="item.name" type="royal"></uni-tag>
									</view>
								</uni-td> -->
								<!-- 			<uni-td align="center">{{item.sort}}</uni-td>
								<uni-td align="center">{{options.status_valuetotext[item.status]}}</uni-td> -->
								<uni-td align="center">
									<view class="uni-group">
										<button class="uni-button" type="primary" @click="useMechanism(item)">
											授权
										</button>
										<!-- 	<button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button"
											size="mini" type_drive_id type="primary">修改</button>
										<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
											type="warn">删除</button>
										<button class="uni-button" type="primary" size="mini"
											@click="befordownload(index)">导出
											Excel</button> -->
									</view>
								</uni-td>
							</uni-tr>
						</uni-table>

						<!-- 		<download-excel ref="excelDownload" v-show="false" class="hide-on-phone" :fields="exportExcel.fields"
							:data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
				
						</download-excel> -->


						<view class="uni-pagination-box">
							<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
								:total="pagination.count" @change="onPageChanged" />
						</view>
					</unicloud-db>
				</view>
			</view>

			<view>
				<view class="right-conten">
					<view class="uni-container" style="max-height: 60vh;overflow: scroll;">
						<!-- <unicloud-db ref="udb_mechanism_subject" :collection="loadRightData"
							field="_id,mechanism_id{_id,name},subject_id{_id,s_id,name}" page-data="replace"
							:orderby="orderby" :getcount="true" :page-size="optionsOfMechanismSubject.pageSize"
							:page-current="optionsOfMechanismSubject.pageCurrent"
							v-slot:default="{data,pagination,loading,error,options}"
							:options="optionsOfMechanismSubject" loadtime="manual"> -->
							<uni-table ref="tableMechanismList"  type="selection" @selection-change="selectionChangeMechanism">
								<!-- <uni-tr>
									<uni-th align="center" sortable @sort-change="sortChange($event, 'mechanism_id')">
										所属机构
									</uni-th>
									<uni-th align="center" sortable @sort-change="sortChange($event, 'subject_id')">授权题库
									</uni-th>
								</uni-tr> -->

										<uni-tr>
												<uni-th>
													课程
												</uni-th>
												<uni-th>
													操作
												</uni-th>
											</uni-tr>

								<uni-tr v-for="(item,index) in subjectIdlist" :key="index">
									<!-- <uni-td align="center">{{item.mechanism_id && item.mechanism_id[0].name}}</uni-td> -->


										<!-- <uni-table type="selection" @selection-change="selectionChangeMechanism"> -->
											<!-- <uni-tr>
												<uni-th>
													课程
												</uni-th>
												<uni-th>
													操作
												</uni-th>
											</uni-tr> -->
												<uni-td>
													<uni-tag :text="item.name">
													</uni-tag>
												</uni-td>

												<uni-td align="center">
													<view class="uni-group">
														<button @click="confirmDeleteForMechanismList(item.s_id)"
															class="uni-button" size="mini" type="warn">取消</button>
													</view>
												</uni-td>
										<!-- </uni-table> -->



								</uni-tr>
							</uni-table>
							<!-- <view class="uni-pagination-box">
								<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
									:total="pagination.count" @change="onPageChanged" />
							</view> -->
						<!-- </unicloud-db> -->
					</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '../../js_sdk/validator/subject-page.js';
	import * as XLSX from '@/js_sdk/xlsx/dist/xlsx.full.min.js'
	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = '' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}
	export default {
		props: {
			mechanismId: {
				type: String,
				default: '',
				require: true
			}
		},
		data() {
			return {
				subjectIdlist:[],
				//mechanism_list:[],
				mechanismListWhere: {},
				cachedata: [],
				collectionList: "subject-page,type-drive,test-paper,type-subject",
				collection: [db.collection('mechanism-subject-list').where({
						'mechanism_id': this.mechanismId
					}).getTemp(),
					db.collection('mechanism').where({
						_id: this.mechanismId
					}).getTemp(),
					db.collection('subject-page').getTemp()
				],
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],

				mechanismSubjectSelectIndexs: [],
				optionsOfMechanismSubject: {
					pageSize,
					pageCurrent,
				},
				options: {
					pageSize,
					pageCurrent,
					filterData: {
						"status_localdata": [{
								"text": "正常",
								"value": 0
							},
							{
								"text": "禁用",
								"value": 1
							}
						]
					},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "subject-page.xls",
					"type": "xls",
					"fields": {
						"课程ID": "s_id",
						"课程昵称": "name",
						"科目类型": "type_subject",
						"驾驶证类型": "type_drive_id",
						"视频链接": "video_link",
						"视频昵称": "video_name",
						"试卷": "test_paper_ids",
						"排序": "sort",
						"启用状态": "status",
						"试卷排序": "t_sort"
					}
				},
				templdateData:null,
				exportExcelData: []
			}
		},

		created() {
			this._filter = {}
			console.log(this.mechanismId)
			this.loadMerData()

		},
		mounted() {
			this.$refs.udb.loadData()
			this.mechanismListWhere["mechanism_id"] = db.command.eq(this.mechanismId)

			this.$nextTick(() => {
				console.log(this.mechanismId)
			//	this.$refs.udb_mechanism_subject.loadData()
			//    this.loadRightData(
			//  this.cleanAll()
			   this.loadRightData()
			})
		},
		methods: {
			async cleanAll (){
				const list =await db.collection('mechanism-subject-list').where({
						'subject_id': {$size:1}
					}).get(500)
				const dele = list.result.data.map(async (e)=>{
					 await db.collection('mechanism-subject-list').where({
						'_id': e._id
					}).remove()
					return e.mechanism_id
				})
				console.log(dele)
			
			},
			async loadRightData(){
				const collection = await db.collection('mechanism-subject-list').where({
						'mechanism_id': this.mechanismId
					}).get()
				if(collection.result.data.length>0){
					console.log('collection',collection)
				const d =	await db.collection('subject-page').where({
					's_id': db.command.in(collection.result.data[0].subject_id)
					}).get(500)
					// console.log(d.result.data)
					this.subjectIdlist = d.result.data
					this.templdateData = collection.result.data[0]
					return  d.result.data 
				}else{
					return [] 
				}
				
			},
			async loadMerData() {
				try{
					const db = uniCloud.databaseForJQL()
					const mesub =  db.collection('mechanism-subject-list').where({
						'mechanism_id': db.command.eq(this.mechanismId)
					}).getTemp()
			
					const me = db.collection('mechanism').where({
						_id: db.command.eq(this.mechanismId)
					}).getTemp()             
					const sub = await db.collection('subject-page').getTemp()
					const lst = await db.collection(mesub, me).get()
					console.log(lst)
					return 
				}catch(e){
					console.error(e)
				}
				
			},
			async useMechanism(item) {
				const {
					s_id,
					name
				} = item
				const self = this

				const cur_mechanism = this.templdateData
				if (cur_mechanism != null) {

					let arr = []
					cur_mechanism.subject_id.forEach((e) => {
						arr.push(e)
					})
					if (arr.includes(s_id)) {
						uni.showToast({
							title: '已经添加无需在授权',
							duration: 1500
						})
						console.log(arr.indexOf(s_id))
						return
					}
					arr.push(s_id)
					console.log('arr',arr)

					const res = await db.collection('mechanism-subject-list').
					where({
						_id:cur_mechanism._id
					}).update({
						subject_id:arr
					})
					if(res){
						this.loadRightData()
						uni.showToast({
							title:'授权成功',
							duration:2000,
							icon:'none'
						})
					}
					// this.$refs.udb_mechanism_subject.update(cur_mechanism._id, {
					// 	subject_id: arr
					// }, {
					// 	complete: () => {
					// 		self.$refs.udb_mechanism_subject.refresh()
					// 	}
					// })

				} else {
					uni.showLoading({
						title: 'loading'
					})
					await db.collection('mechanism-subject-list').add({
						mechanism_id: this.mechanismId,
						subject_id: [s_id]
					}, {
						toastTitle: '授权成功',
						success: (res) => {
							console.log(res)
							const {
								code,
								meesage
							} = res
						},
						fail: (err) => {
							uni.showToast({
								title: err,
								duration: 1500
							})
						},
						complete: () => { // 完成后的回调
							uni.hideLoading()
							self.$refs.udb_mechanism_subject.refresh()
						}
					})
				}
			},
			/**
			 * 
			 * 	"课程ID": "s_id",
			"课程昵称": "name",
			"科目类型": "type_subject",
			"驾驶证类型": "type_drive_id",
			"视频链接": "video_link",
			"视频昵称": "video_name",
			"试卷": "test_paper_ids",
			"排序": "sort",
			"试卷排序":"t_sort",
			"启用状态": "status"
			 */

			async befordownload(index) {
				// this.exportExcelData
				this.exportExcelData = []
				let type_drive = this.cachedata[index]['type_drive_id']
				let c = type_drive.map(v => v.s_id)
				let type_subject = this.cachedata[index]['type_subject']
				let s = type_subject.map(v => v.s_id)

				let header = {
					"s_id": this.cachedata[index]['s_id'],
					"name": this.cachedata[index]['name'],
					"type_subject": s.join('|'),
					"type_drive_id": c.join('|'),
					"video_name": this.cachedata[index]['video_name'][0],
					"video_link": this.cachedata[index]['video_link'][0],
					"test_paper_ids": this.cachedata[index]['test_paper_ids'][0].s_id,
					"t_sort": this.cachedata[index]['t_sort'][0]
				}
				this.exportExcelData.push(header)
				for (let i = 1; i < this.cachedata[index]['test_paper_ids'].length; i++) {
					this.exportExcelData.push({
						"video_link": this.cachedata[index]['video_link'][i],
						"video_name": this.cachedata[index]['video_name'][i],
						"test_paper_ids": this.cachedata[index]['test_paper_ids'][i].s_id,
						"t_sort": this.cachedata[index]['t_sort'][i]
					})
				}

				this.$nextTick(async () => {
					await this.$refs.excelDownload.generate()
				})



			},
			onqueryload(data) {
				this.cachedata = this.$cloneObject(data)
			},

			// onqueryload(data) {
			//   this.exportExcelData = data
			// },
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			selectionChangeMechanism(e) {
				this.mechanismSubjectSelectIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			confirmDeleteForMechanismList(id) {

				const self = this
				uni.showModal({
					content: "是否取消授权?",
					success(res) {

						if (res) {
							const list = self.$refs.udb_mechanism_subject.dataList
							let cur_mechanism = list[0]
							let delPosition = 0
							let upsubjectIds = []
							cur_mechanism.subject_id.forEach((e, i) => {
								if (id === e.s_id) {
									delPosition = i
								}
								upsubjectIds.push(e.s_id)
							})
							upsubjectIds.splice(delPosition, 1)
							console.log(upsubjectIds)
							self.$refs.udb_mechanism_subject.update(cur_mechanism._id, {
								subject_id: upsubjectIds
							}, {
								complete: () => {
									this.loadRightData()
									//self.$refs.udb_mechanism_subject.refresh()
								}
							})
						}
					}
				})

			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},

			uploadExcel() {
				const self = this
				uni.chooseFile({
					async success(res) {

						const url = res.tempFilePaths[0];
						const data = await (await fetch(url, {
							mode: 'no-cors'
						})).arrayBuffer();
						/* data is an ArrayBuffer */
						const workbook = XLSX.read(data);
						const xlsxData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
						let keyMap = Object.keys(self.exportExcel.fields)
						// console.log(xlsxData)

						/**
						 * 
						 * 	"课程ID": "s_id",
						"课程昵称": "name",
						"科目类型": "type_subject",
						"驾驶证类型": "type_drive_id",
						"视频链接": "video_link",
						"视频昵称": "video_name",
						"试卷": "test_paper_ids",
						"排序": "sort",
						"启用状态": "status"
						 */

						let header = {
							s_id: xlsxData[0]['课程ID'].toString(),
							name: xlsxData[0]['课程昵称'].toString(),
							type_subject: xlsxData[0]['科目类型'].toString(),
							type_drive_id: xlsxData[0]['驾驶证类型'].split('|'),
							t_sort: [],
							video_link: [],
							video_name: [],
							test_paper_ids: [],
							status: 0
						}
						if (xlsxData[0]['视频链接']) {
							header.video_link.push(xlsxData[0]['视频链接'])
						}
						if (xlsxData[0]['视频昵称']) {
							header.video_name.push(xlsxData[0]['视频昵称'])
						}
						header.test_paper_ids.push(xlsxData[0]['试卷ID'].toString())
						header.t_sort.push(xlsxData[0]['试卷排序'])
						for (let i = 1; i < xlsxData.length; i++) {
							if (xlsxData[0]['视频链接']) {
								header.video_link.push(xlsxData[i]['视频链接'])
							}
							if (xlsxData[0]['视频昵称']) {
								header.video_name.push(xlsxData[i]['视频昵称'])
							}
							header.test_paper_ids.push(xlsxData[i]['试卷ID'].toString())
							header.t_sort.push(xlsxData[i]['试卷排序'])
						}

						const q_list = await db.collection('test-paper').where({
								s_id: db.command.in(header.test_paper_ids)
							})
							.groupBy('s_id')
							.limit(1000)
							.get()
						console.log(q_list)

						let map = new Map()
						let notId = []
						for (let row of q_list.result.data) {
							map.set(row.s_id, true)
						}
						for (let row of header.test_paper_ids) {
							if (!map.has(row)) {
								notId.push(row)
							}
						}
						if (notId.length > 0) {
							uni.showModal({
								content: "试卷集合:" + notId.join(',') + "不存在",
								showCancel: false,
								confirmText: '复制错误信息',
								success(res) {
									if (res.confirm) {
										uni.setClipboardData({
											data: notId.join(','),
											success(info) {
												uni.showToast({
													title: '复制成功',
													duration: 1500,
													icon: 'none'
												})
											}
										})
									}
								}
							})
							return;
						}

						await db.collection('subject-page').add(header).then((res) => {
							uni.showToast({
								title: '新增成功'
							})
							self.$nextTick(() => {
								self.$refs.udb.refresh()
							})
						}).catch((err) => {
							console.log(err)
							uni.showModal({
								content: err.message,
								showCancel: false
							})
						})

					}
				})

			}

		}
	}
</script>

<style lang="scss">
	.uni-content {
		height: 80vh;
		overflow: scroll;
	}

	.uni-container {
		background-color: #fff;
		display: flex;
		flex-direction: row;
		height: 80vh;
	}

	.left-content {
		max-height: 60vh;
		overflow-y: scroll;
	}

	.right-content {}
</style>